﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SoufunData.DB;

namespace SoufunData
{
    public partial class ExToDbZOpeningMonitor : DevExpress.XtraEditors.XtraForm
    {
        public ExToDbZOpeningMonitor()
        {
            InitializeComponent();
        }

        private void btn_excelPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;
            btn_excelPath.Text = fileName;

            gridControl2.DataSource = null;
            gridView2.Columns.Clear();
            gridView2.GroupPanelText = "请选择Excel文件";
            if (fileName == "")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds == null || ds.Tables.Count == 0)
            {
                string strError = "读取Excel时发生错误，请核对：\r\n ";
                strError += "1，导入时请在Excel中关闭想要导入的文件！\r\n";
                strError += "2，导入的Excel表中的工作表名称必须为Sheet1,否者程序无法读取！\r\n";
                strError += "3，请确保您的计算机安装了Microsoft Office！\r\n";
                strError += "4，请确保导入的Excel文件正常！";
                XtraMessageBox.Show(strError);
                btn_excelPath.Text = "";
                return;
            }
            if (!CheckExcelColumnsName(ds.Tables[0]))
            {
                btn_excelPath.Text = "";
                return;
            }
            gridControl2.DataSource = ds.Tables[0];
            gridView2.GroupPanelText = "共有" + ds.Tables[0].Rows.Count + "条数据";
        }


        private void AddData()
        {
           
            DataTable dtOld = (DataTable)gridControl2.DataSource;

            DataTable dt = dtOld.Copy();
            dt.Rows.Clear();
            foreach (DataRow dataRow in dtOld.Rows)
            {
                dt.Rows.Add(dataRow.ItemArray);
            }
             
            int insertRowsCount = 500;//一次性插入数据库行数
            int succeedrows = 0;//成功插入数据行数
            StringBuilder strSql = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                string strProjectName = row["项目名称"].ToString();
                string strAdVern = row["行政区"].ToString();
                string strOpeningTime = row["开盘时间"].ToString();
                string strPublicBuilding = row["推出楼栋"].ToString();
                string strLiftHouse = row["梯户比"].ToString();
                string strPubHouseType = row["推出户型"].ToString();
                string strPubHouseArea = row["推出户型面积"].ToString();
                string strPubHouseCount = row["推出套数"].ToString();
                string strSaleHouseCount = row["成交套数"].ToString();
                string strSellingRate = row["去化率"].ToString();
                string strPropertyType = row["物业类型"].ToString();
                string strOpeningPrice = row["开盘价格"].ToString();
                string strOpeningFavourable = row["开盘优惠"].ToString();
                string strOpeningType = row["开盘方式"].ToString();
                string strVisitCustomCount = row["到访客户数"].ToString();
                string strVisitCustomAge = row["到访客户年龄"].ToString();
                string strOpeningScene = row["开盘现场情况描述"].ToString();
                string strOpeningSceneImage = row["开盘情况附图"].ToString();
                if (strSaleHouseCount.Trim() == "")
                {
                    strSaleHouseCount = "0";
                }

                if (i % insertRowsCount == 0)
                {
                    strSql = new StringBuilder();
                    strSql.Append("Insert into tzopeningmonitor(");
                    strSql.Append("ProjectName,");
                    strSql.Append("AdministratiVeregion,");
                    strSql.Append("OpeningTime,");
                    strSql.Append("PublicBuilding,");
                    strSql.Append("LiftHouse,");
                    strSql.Append("PublicHouseType,");
                    strSql.Append("PublicHouseArea,");
                    strSql.Append("PublicHouseCount,");
                    strSql.Append("SaleHouseCount,");
                    strSql.Append("SellingRate,");
                    strSql.Append("PropertyType,");
                    strSql.Append("OpeningPrice,");
                    strSql.Append("OpeningFavourable,");
                    strSql.Append("OpeningType,");
                    strSql.Append("VisitCustomCount,");
                    strSql.Append("VisitCustomAge,");
                    strSql.Append("OpeningScene,");
                    strSql.Append("OpeningSceneImage");                                         
                    strSql.Append(") value  ");
                }
                strSql.Append("(");
                strSql.Append("'");
                strSql.Append(strProjectName);
                strSql.Append("','");
                strSql.Append(strAdVern);
                strSql.Append("','");
                strSql.Append(strOpeningTime);
                strSql.Append("','");
                strSql.Append(strPublicBuilding);
                strSql.Append("','");
                strSql.Append(strLiftHouse);
                strSql.Append("','");
                strSql.Append(strPubHouseType);
                strSql.Append("','");
                strSql.Append(strPubHouseArea);
                strSql.Append("',");
                strSql.Append(strPubHouseCount);
                strSql.Append(",");
                strSql.Append(strSaleHouseCount);
                strSql.Append(",'");
                strSql.Append(strSellingRate);
                strSql.Append("','");
                strSql.Append(strPropertyType);
                strSql.Append("','");
                strSql.Append(strOpeningPrice);
                strSql.Append("','");
                strSql.Append(strOpeningFavourable);
                strSql.Append("','");
                strSql.Append(strOpeningType);
                strSql.Append("','");
                strSql.Append(strVisitCustomCount);
                strSql.Append("','");
                strSql.Append(strVisitCustomAge);
                strSql.Append("','");
                strSql.Append(strOpeningScene);
                strSql.Append("','");
                strSql.Append(strOpeningSceneImage);
                strSql.Append("'),");

                if ((i + 1) % insertRowsCount == 0
                    || i == dt.Rows.Count - 1)
                {
                    strSql.Remove(strSql.Length - 1, 1);
                    try
                    {
                        succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show("数据库错误：" + ex.Message);
                    }
                     
                }
            }

            if (dt.Rows.Count == succeedrows)
            {
                XtraMessageBox.Show("添加成功！");
                BeginInvoke(new MethodInvoker(() =>
                {
                    btn_excelPath.Text = "";
                    gridControl2.DataSource = null;
                }));
            }
            else
            {
                int failedCount = dt.Rows.Count - succeedrows;
                XtraMessageBox.Show("共记" + dt.Rows.Count + "条数据，其中"
                    + failedCount + "条数据添加失败！");
            }
            BeginInvoke(new MethodInvoker(() =>
            {
               
                btn_excelPath.Enabled = true;
                btn_add.Enabled = true;
            }));
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (btn_excelPath.Text.Trim()=="")
            {
                XtraMessageBox.Show("请先选择Excel！");
                return;
            }
            if (!CheckDataValid())
            {
                return;
            }
             
            btn_excelPath.Enabled = false;
            btn_add.Enabled = false;
            Thread t = new Thread(AddData) { IsBackground = true };
            t.Start();
        }

        #region 数据完整性检测
        private bool CheckDataValid()
        {
            DataTable dt = (DataTable)gridControl2.DataSource;
            StringBuilder strErrors = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string strProName = dr["项目名称"].ToString();
                string strXzq = dr["行政区"].ToString();
                string strOpenTime = dr["开盘时间"].ToString();
                string strPubCount = dr["推出套数"].ToString();
                string strSellCount = dr["成交套数"].ToString();

                if (strProName.Trim() == "")
                {
                    strErrors.Append("第" + (i + 1) + "行数据中的【项目名称】为空！\r\n");
                }
                if (strXzq.Trim() == "")
                {
                    strErrors.Append("第" + (i + 1) + "行数据中【行政区】未填！\r\n");
                }                 
                DateTime tempTime = new DateTime();
                if (!DateTime.TryParse(strOpenTime, out tempTime))
                {
                    strErrors.Append("第" + (i + 1)
                   + "行数据中【开盘时间】的数据格式有误，应为时间格式【yyyy年MM月dd日】！\r\n");
                }
                int intTemp = 0;
                if (!int.TryParse(strPubCount,out intTemp))
                {
                    strErrors.Append("第" + (i + 1) + "行数据中【推出套数】不为正确的整数格式！\r\n");
                }
                else
                {
                    if (int.Parse(strPubCount)<=0)
                    {
                        strErrors.Append("第" + (i + 1) + "行数据中【推出套数】数据有错误，必须为大于0的整数！\r\n");
                    }                    
                }
                if (strSellCount.Trim()!="" &&
                    !int.TryParse(strSellCount, out intTemp))
                {
                    strErrors.Append("第" + (i + 1) + "行数据中【成交套数】不为正确的数字格式！\r\n");
                }
            }
            if (strErrors.ToString() != "")
            {
                XtraMessageBox.Show("您选择的Excel中的数据存在以下错误：\r\n" +
                    strErrors);
                return false;
            }
            return true;
        }

        private bool CheckExcelColumnsName(DataTable dt)
        {
            StringBuilder strErrors = new StringBuilder();
            if (!dt.Columns.Contains("项目名称"))
            {
                strErrors.Append("【项目名称】、");
            }
            if (!dt.Columns.Contains("行政区"))
            {
                strErrors.Append("【行政区】、");
            }
            if (!dt.Columns.Contains("开盘时间"))
            {
                strErrors.Append("【开盘时间】、");
            }
            if (!dt.Columns.Contains("推出楼栋"))
            {
                strErrors.Append("【推出楼栋】、");
            }
            if (!dt.Columns.Contains("梯户比"))
            {
                strErrors.Append("【梯户比】、");
            }
            if (!dt.Columns.Contains("推出户型"))
            {
                strErrors.Append("【推出户型】、");
            }
            if (!dt.Columns.Contains("推出户型面积"))
            {
                strErrors.Append("【推出户型面积】、");
            }
            if (!dt.Columns.Contains("推出套数"))
            {
                strErrors.Append("【推出套数】、");
            }
            if (!dt.Columns.Contains("成交套数"))
            {
                strErrors.Append("【成交套数】、");
            }
            if (!dt.Columns.Contains("去化率"))
            {
                strErrors.Append("【去化率】、");
            }
            if (!dt.Columns.Contains("物业类型"))
            {
                strErrors.Append("【物业类型】");
            }
            if (!dt.Columns.Contains("开盘价格"))
            {
                strErrors.Append("【开盘价格】");
            }
            if (!dt.Columns.Contains("开盘优惠"))
            {
                strErrors.Append("【开盘优惠】");
            }
            if (!dt.Columns.Contains("开盘方式"))
            {
                strErrors.Append("【开盘方式】");
            }
            if (!dt.Columns.Contains("到访客户数"))
            {
                strErrors.Append("【到访客户数】");
            }
            if (!dt.Columns.Contains("到访客户年龄"))
            {
                strErrors.Append("【到访客户年龄】");
            }
            if (!dt.Columns.Contains("开盘现场情况描述"))
            {
                strErrors.Append("【开盘现场情况描述】");
            }
            if (!dt.Columns.Contains("开盘情况附图"))
            {
                strErrors.Append("【开盘情况附图】");
            }
            if (strErrors.ToString() != "")
            {
                XtraMessageBox.Show("您选择的广告投放Excel表数据不正常,缺少以下数据列:\r\n" +
                                    strErrors);
                return false;
            }
            return true;
        }
        #endregion
         
    }
}